﻿using System;
using Ntt.NttData.Been.CommonLibrary.Database.SqlServer;
using System.Data;

namespace NTTDATA.BEENChina.CaseMonitor.CaseChecker
{
    [Serializable]
    public class Relay : Note
    {
        public String Sql
        {
            get { return ConstructSql(); } 
        }

        private String GetDBconnString(){
            Log.Console.Info(Address);
            return String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", this.Address,DBName,UserId,PassWord);
        }
        
        protected override int calcCount()
        {
            int count = 0;
            try
            {
                int.TryParse(new SqlHelper().ExecuteScalar(GetDBconnString(), CommandType.Text, Sql).ToString(), out count);

                Log.Console.Debug(string.Format("Realy Address:{0}{3}  Count:{1}{3}  Sql:{2}", Address, count, Sql, Environment.NewLine));
                


            }
            catch (Exception ex)
            {
                Log.Console.Error(string.Format("Relay Address:{0}{3}  Count:{1}{3}  Sql:{2}", Address, count, Sql, Environment.NewLine));
                Log.Console.Error("CaseChecker Management Relay", ex);
            }
           
          
           return count;
        }

        /// <summary>
        /// {0}: 需要调整的时间 分钟，整型
        ///      正数 往后调整;负数 往前调整
        /// {1}: 调整后的开始时刻 ex: 01:00:00 
        /// {2}: 调整后的开始时刻 ex: 05:00:00 
        /// </summary>
        /// <returns>sql</returns>
        private String ConstructSql()
        {


            String sql = "SELECT COUNT(*)  FROM t_OrderData WITH(NOLOCK) " +
                   "WHERE CustomerCode='{3}' AND "+
                   " DATEADD( mi, {0},[OridSendTime])  BETWEEN '{4} {1}' AND '{4} {2}'";
                   //" LEFT( CONVERT(NVARCHAR(19), DATEADD( mi, {0},[OridSendTime]),120),16) BETWEEN '{4} {1}' AND '{4} {2}'";

            String tuneMi =  String.IsNullOrEmpty(base.TuneMi.Trim()) ? "0" :base.TuneMi;

            String now = System.DateTime.Now.ToString("HH:mm");

            sql = String.Format(sql, tuneMi,DateFrom, String.IsNullOrEmpty(DateTo)? now :DateTo, CustomerID,System.DateTime.Now.ToString("yyyy-MM-dd"));

            return sql;
        }

    }
}